package com.adminkk.handler;

import com.adminkk.scan.FileScaner;
import com.adminkk.scan.Scaner;
import com.adminkk.scan.XmlScaner;
import com.adminkk.tools.ParameterNameUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final  class HandlerMapping {


    private static  final Map<String,Handler> handlerMapping = new HashMap<String, Handler>();

    private static  final List<Scaner> scaners = new ArrayList<>(2);
    static {
        scaners.add(new XmlScaner());
        scaners.add(new FileScaner());
    }

    public  static void scanPackage(String scanUrl) throws RuntimeException, IllegalAccessException, InstantiationException, ClassNotFoundException {

        for (Scaner scaner : scaners) {
            scaner.doScane(scanUrl);
        }

    }




    public static void doInit(String scanUrl) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        scanPackage(scanUrl);
    }



    public static void doService(HttpServletRequest request, HttpServletResponse response) {

        String requestURI = request.getRequestURI();
        System.out.println("请求地址是="+ requestURI);
        Handler handler = handlerMapping.get(requestURI);
        if(handler == null){
            System.out.println("请求地址是="+ requestURI+" 没有配置改路径");
            return;
        }
        Method method = handler.getMethod();
        Object instance = handler.getInstance();
        response.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;

        try {

            //这里是简单的解析 可以像springmvc那样解析处理
            Map<String, String[]> parameterMap = request.getParameterMap();
            String[] parameters = ParameterNameUtils.getParameterNamesByJavassist(instance.getClass(),method);
            Object[]  parameter = new Object[parameters.length];
            if(parameters != null && parameters.length > 0){
                for (int i = 0; i < parameters.length; i++) {
                    final String simpleName = parameters[i];
                    StringBuilder parameterSb = new  StringBuilder();
                    final String[] parameterStr = parameterMap.get(simpleName);
                    if(parameterStr != null){
                        for (int j = 0; j < parameterStr.length; j++) {
                            parameterSb.append(parameterStr[j]);
                        }
                    }
                    parameter[i] = parameterSb.toString();
                }
            }

            writer = response.getWriter();
            String result = (String) method.invoke(instance,parameter);
            writer.print(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求地址是="+ requestURI+" 执行异常");
            writer.print("业务执行异常");
        }finally {
            writer.flush();
            writer.close();
        }
    }

    public static Handler addHandlerMapping(String url,Handler handler) {
        return handlerMapping.put(url,handler);
    }

    public static Handler getHandlerMapping(String url) {
        return handlerMapping.get(url);
    }



}
